package com.ruoyi.tzai.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.tzai.domain.AIModelConfig;
import com.ruoyi.tzai.domain.ApiKeyPool;
import com.ruoyi.tzai.mapper.ApiKeyPoolMapper;
import com.ruoyi.tzai.service.IApiKeyPoolService;
import com.ruoyi.tzai.service.IAIModelConfigService;

/**
 * API Key池Service业务层处理
 * 
 * @author tzai
 * @date 2025-11-12
 */
@Service
public class ApiKeyPoolServiceImpl implements IApiKeyPoolService 
{
    private static final Logger log = LoggerFactory.getLogger(ApiKeyPoolServiceImpl.class);

    @Autowired
    private ApiKeyPoolMapper apiKeyPoolMapper;

    @Autowired
    private IAIModelConfigService aiModelConfigService;

    /**
     * 查询API Key池
     * 
     * @param keyId API Key池主键
     * @return API Key池
     */
    @Override
    public ApiKeyPool selectApiKeyPoolByKeyId(Long keyId)
    {
        return apiKeyPoolMapper.selectApiKeyPoolByKeyId(keyId);
    }

    /**
     * 查询API Key池列表
     * 
     * @param apiKeyPool API Key池
     * @return API Key池
     */
    @Override
    public List<ApiKeyPool> selectApiKeyPoolList(ApiKeyPool apiKeyPool)
    {
        return apiKeyPoolMapper.selectApiKeyPoolList(apiKeyPool);
    }

    /**
     * 新增API Key池
     * 
     * @param apiKeyPool API Key池
     * @return 结果
     */
    @Override
    public int insertApiKeyPool(ApiKeyPool apiKeyPool)
    {
        apiKeyPool.setCreateTime(DateUtils.getNowDate());
        return apiKeyPoolMapper.insertApiKeyPool(apiKeyPool);
    }

    /**
     * 修改API Key池
     * 
     * @param apiKeyPool API Key池
     * @return 结果
     */
    @Override
    public int updateApiKeyPool(ApiKeyPool apiKeyPool)
    {
        apiKeyPool.setUpdateTime(DateUtils.getNowDate());
        return apiKeyPoolMapper.updateApiKeyPool(apiKeyPool);
    }

    /**
     * 批量删除API Key池
     * 
     * @param keyIds 需要删除的API Key池主键
     * @return 结果
     */
    @Override
    public int deleteApiKeyPoolByKeyIds(Long[] keyIds)
    {
        return apiKeyPoolMapper.deleteApiKeyPoolByKeyIds(keyIds);
    }

    /**
     * 删除API Key池信息
     * 
     * @param keyId API Key池主键
     * @return 结果
     */
    @Override
    public int deleteApiKeyPoolByKeyId(Long keyId)
    {
        return apiKeyPoolMapper.deleteApiKeyPoolByKeyId(keyId);
    }

    /**
     * 获取单个可用Key（智能负载均衡）
     * 
     * @param resourceType 资源类型
     * @param resourceId 资源ID
     * @return API Key信息
     */
    @Override
    @Transactional
    public ApiKeyPool acquireKey(String resourceType, Long resourceId)
    {
        // 获取可用Key列表（已按优先级、负载、响应时间排序）
        List<ApiKeyPool> availableKeys = apiKeyPoolMapper.selectAvailableKeys(resourceType, resourceId, 1);
        
        if (availableKeys == null || availableKeys.isEmpty()) {
            log.warn("没有可用的Key: resourceType={}, resourceId={}", resourceType, resourceId);
            return null;
        }
        
        ApiKeyPool key = availableKeys.get(0);
        
        // 原子性增加使用数
        int updated = apiKeyPoolMapper.incrementKeyUsage(key.getKeyId());
        if (updated > 0) {
            log.debug("获取Key成功: keyId={}, keyName={}, currentConcurrency={}/{}", 
                     key.getKeyId(), key.getKeyName(), 
                     key.getCurrentConcurrency() + 1, key.getMaxConcurrency());
            
            // 更新内存中的使用数
            key.setCurrentConcurrency(key.getCurrentConcurrency() + 1);
            return key;
        } else {
            log.warn("Key已被占用: keyId={}", key.getKeyId());
            return null;
        }
    }

    /**
     * 获取多个可用Key（用于并行处理）
     * 
     * @param resourceType 资源类型
     * @param resourceId 资源ID
     * @param count 需要的Key数量
     * @return Key列表
     */
    @Override
    @Transactional
    public List<ApiKeyPool> acquireKeys(String resourceType, Long resourceId, int count)
    {
        List<ApiKeyPool> acquiredKeys = new ArrayList<>();
        
        // 查询可用Key（查询比需要数量多一些，防止并发占用）
        List<ApiKeyPool> availableKeys = apiKeyPoolMapper.selectAvailableKeys(
            resourceType, resourceId, count * 2);
        
        if (availableKeys == null || availableKeys.isEmpty()) {
            log.warn("没有可用的Key: resourceType={}, resourceId={}", resourceType, resourceId);
            return acquiredKeys;
        }
        
        // 尝试获取指定数量的Key
        for (ApiKeyPool key : availableKeys) {
            if (acquiredKeys.size() >= count) {
                break;
            }
            
            // 原子性增加使用数
            int updated = apiKeyPoolMapper.incrementKeyUsage(key.getKeyId());
            if (updated > 0) {
                key.setCurrentConcurrency(key.getCurrentConcurrency() + 1);
                acquiredKeys.add(key);
                log.debug("获取Key: keyId={}, keyName={}, usage={}/{}", 
                         key.getKeyId(), key.getKeyName(),
                         key.getCurrentConcurrency(), key.getMaxConcurrency());
            }
        }
        
        log.info("获取到 {} 个可用Key (需要 {} 个): resourceType={}, resourceId={}", 
                 acquiredKeys.size(), count, resourceType, resourceId);
        
        return acquiredKeys;
    }

    /**
     * 获取跨资源的可用Key（仅用于AI翻译跨模型）
     * 
     * @param resourceIds 允许使用的资源ID列表，空=所有启用资源
     * @param count 需要的Key数量
     * @return Key列表
     */
    @Override
    @Transactional
    public List<ApiKeyPool> acquireKeysAcrossModels(List<Long> resourceIds, int count)
    {
        List<ApiKeyPool> acquiredKeys = new ArrayList<>();
        
        // 如果resourceIds为空，获取所有启用的AI模型
        if (resourceIds == null || resourceIds.isEmpty()) {
            AIModelConfig queryConfig = new AIModelConfig();
            queryConfig.setStatus("0"); // 启用状态
            List<AIModelConfig> enabledModels = aiModelConfigService.selectAIModelConfigList(queryConfig);
            
            resourceIds = enabledModels.stream()
                                      .map(AIModelConfig::getModelId)
                                      .collect(Collectors.toList());
            
            if (resourceIds.isEmpty()) {
                log.warn("没有启用的AI模型");
                return acquiredKeys;
            }
            
            log.info("使用所有启用的AI模型: {}", resourceIds);
        }
        
        // 查询跨资源的可用Key
        List<ApiKeyPool> availableKeys = apiKeyPoolMapper.selectAvailableKeysAcrossResources(
            "ai_model", resourceIds, count * 2);
        
        if (availableKeys == null || availableKeys.isEmpty()) {
            log.warn("没有可用的Key: resourceIds={}", resourceIds);
            return acquiredKeys;
        }
        
        // 尝试获取指定数量的Key
        for (ApiKeyPool key : availableKeys) {
            if (acquiredKeys.size() >= count) {
                break;
            }
            
            // 原子性增加使用数
            int updated = apiKeyPoolMapper.incrementKeyUsage(key.getKeyId());
            if (updated > 0) {
                key.setCurrentConcurrency(key.getCurrentConcurrency() + 1);
                acquiredKeys.add(key);
                log.debug("获取跨模型Key: keyId={}, resourceId={}, keyName={}", 
                         key.getKeyId(), key.getResourceId(), key.getKeyName());
            }
        }
        
        log.info("跨模型获取到 {} 个可用Key (需要 {} 个)，来自 {} 个模型", 
                 acquiredKeys.size(), count, 
                 acquiredKeys.stream().map(ApiKeyPool::getResourceId).distinct().count());
        
        return acquiredKeys;
    }

    /**
     * 释放Key
     * 
     * @param keyId Key ID
     */
    @Override
    @Transactional
    public void releaseKey(Long keyId)
    {
        if (keyId == null) {
            return;
        }
        
        int updated = apiKeyPoolMapper.decrementKeyUsage(keyId);
        if (updated > 0) {
            log.debug("释放Key: keyId={}", keyId);
        } else {
            log.warn("释放Key失败: keyId={}", keyId);
        }
    }

    /**
     * 标记Key为限流状态
     * 
     * @param keyId Key ID
     * @param seconds 限流秒数
     */
    @Override
    @Transactional
    public void markRateLimited(Long keyId, int seconds)
    {
        if (keyId == null) {
            return;
        }
        
        int updated = apiKeyPoolMapper.markKeyRateLimited(keyId, seconds);
        if (updated > 0) {
            log.warn("Key已被标记为限流: keyId={}, 恢复时间: {} 秒后", keyId, seconds);
        }
    }

    /**
     * 更新Key统计信息
     * 
     * @param keyId Key ID
     * @param success 是否成功
     * @param error 错误信息
     * @param responseTimeMs 响应时间(毫秒)
     */
    @Override
    @Transactional
    public void updateKeyStats(Long keyId, boolean success, String error, long responseTimeMs)
    {
        if (keyId == null) {
            return;
        }
        
        try {
            // 更新统计信息
            apiKeyPoolMapper.updateKeyStats(keyId, success, responseTimeMs);
            
            // 如果失败且包含限流关键词，标记为限流
            if (!success && error != null) {
                String errorLower = error.toLowerCase();
                if (errorLower.contains("rate limit") || 
                    errorLower.contains("too many requests") ||
                    errorLower.contains("quota exceeded")) {
                    
                    // 标记为限流60秒
                    markRateLimited(keyId, 60);
                }
                
                // 更新最后错误信息
                ApiKeyPool updateKey = new ApiKeyPool();
                updateKey.setKeyId(keyId);
                updateKey.setLastError(error.length() > 500 ? error.substring(0, 500) : error);
                updateKey.setUpdateTime(new Date());
                apiKeyPoolMapper.updateApiKeyPool(updateKey);
            }
            
            log.debug("更新Key统计: keyId={}, success={}, responseTime={}ms", 
                     keyId, success, responseTimeMs);
            
        } catch (Exception e) {
            log.error("更新Key统计失败: keyId={}", keyId, e);
        }
    }

    /**
     * 恢复限流状态的Key（定时任务调用）
     * 
     * @return 恢复的Key数量
     */
    @Override
    @Transactional
    public int recoverRateLimitedKeys()
    {
        try {
            int count = apiKeyPoolMapper.recoverRateLimitedKeys();
            if (count > 0) {
                log.info("恢复 {} 个限流Key", count);
            }
            return count;
        } catch (Exception e) {
            log.error("恢复限流Key失败", e);
            return 0;
        }
    }
}

